package com.example.pets.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pets.MainActivity;
import com.example.pets.R;
import com.example.pets.model.datasource.viewmodel.AuthViewModel;
import com.example.pets.model.entities.database.ShareprefenseUtil;

public class AuthActivity extends AppCompatActivity {
    private EditText editEmail, editPassword;
    private Button btnLogin, btnRegister;
    private AuthViewModel authViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);

        editEmail = findViewById(R.id.edit_email);
        editPassword = findViewById(R.id.edit_password);
        //登录按钮
        btnLogin = findViewById(R.id.btn_login);
        //注册按钮
        btnRegister = findViewById(R.id.btn_register);

        authViewModel = new ViewModelProvider(this).get(AuthViewModel.class);

        authViewModel.getUserLiveData().observe(this, user -> {
            ShareprefenseUtil.getinstanse().insertLoginUser(user);
            Toast.makeText(AuthActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
            navigateToMain();
        });

        authViewModel.getErrorLiveData().observe(this, error -> {
            Toast.makeText(AuthActivity.this, error, Toast.LENGTH_SHORT).show();
        });

        btnLogin.setOnClickListener(v -> {
            String email = editEmail.getText().toString().trim();
            String password = editPassword.getText().toString().trim();
            if (validateInput(email, password)) {
                authViewModel.login(email, password);
            }
        });

        btnRegister.setOnClickListener(v -> {
            String email = editEmail.getText().toString().trim();
            String password = editPassword.getText().toString().trim();
            if (validateInput(email, password)) {
                authViewModel.register(email, password);
            }
        });
    }

    private boolean validateInput(String email, String password) {
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "邮箱不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void navigateToMain() {
        Intent intent = new Intent(AuthActivity.this, MainActivity.class);
        startActivity(intent);
        finish(); // 结束登录页面，防止回退
    }
}


